
package com.lwq.im.chartdemo.endecode;

import cn.hutool.core.util.StrUtil;
import com.lwq.im.chartdemo.bean.RequestBody;
import com.lwq.im.chartdemo.constants.Constants;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufInputStream;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import lombok.extern.slf4j.Slf4j;

import java.io.InputStream;
import java.util.List;


/**
 * 消息解码
 *
 * java 使用 google protobuf 编解码 ： https://blog.csdn.net/zxh87/article/details/73105003
 * js 使用 google protobuf 编解码： https://www.jianshu.com/p/a7e2ce11a74d
 *
 * //对应的Java文件生成命令，非windows系统，把protoc.exe改成protoc即可
 * protoc.exe  --java_out=. RequestBody.proto
 *
 *
 *
 * //对应的Js文件生成命令
 * 1protoc.exe --js_out=import_style=commonjs,binary:. RequestBody.proto
 *
 * 2首先创建一个js文件，命名为exports.js，exports.js文件内容如 var chatProto = require('./RequestBody_pb'); ，导出的js文件指向RequestBody_pb.js文件；
 *
 * 3执行如下 命令
 * npm install -g require
 * npm install -g browserify
 * npm install google-protobuf
 * browserify exports.js > chat.js
 *
 *
 *
 */

@Slf4j
public class MessageDecoder extends MessageToMessageDecoder<BinaryWebSocketFrame> {


    @Override
    protected void decode(ChannelHandlerContext context, BinaryWebSocketFrame frame, List<Object> list) throws Exception {

        log.info("通道{}解码",context.channel().id());
        context.channel().attr(Constants.ChannelAttrKye.PING_COUNT).set(null);

        ByteBuf buffer = frame.content();
        InputStream inputStream = new ByteBufInputStream(buffer);
        RequestBodyProto.RequestBody requestBody = RequestBodyProto.RequestBody.parseFrom(inputStream);


        RequestBody body = new RequestBody();
        if (StrUtil.equals(Constants.OpType.OP_TYPE_PONG, body.getOpType())){
            // 客户端回复的心跳事件，静默处理
            return;
        }
        body.setOpType(requestBody.getOpType());
        body.setTimestamp(requestBody.getTimestamp());
        body.setDeviceId(requestBody.getDeviceId());
        body.setUserId(requestBody.getUserId());
        list.add(body);
    }
}

